﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DepartmentOnline.Models;

namespace DepartmentOnline
{
    public partial class AddGroup : System.Web.UI.Page
    {
        protected DepartmentOnline.Models.Group newGroup;
        protected Plan selectedPlan;

        protected void Page_Load(object sender, EventArgs e)
        {
            using (var context = new departmentEntities())
            {
                try
                {
                    var selected = Convert.ToInt32(PlanList.SelectedValue);
                    selectedPlan = context.Plans.FirstOrDefault(x => x.Id == selected);
                }
                catch(Exception fe)
                {
                    System.Diagnostics.Trace.WriteLine("empty plan");
                }
            }
            newGroup = new DepartmentOnline.Models.Group()
            {
                Number = NumberTB.Text,
                Course = CourseTB.Text,
                StudentsQty = 0
            };
            if(selectedPlan!=null)
            {
                newGroup.Plan = selectedPlan;
            }
            lbName.Text = NumberTB.Text;
        }

        protected void FinishButton_Click(object sender, WizardNavigationEventArgs e)
        {
            using (var context = new departmentEntities())
            {
                if (newGroup != null)
                {
                    try
                    {
                        context.Groups.Add(newGroup);
                        context.SaveChanges();
                    }
                    catch (DbEntityValidationException dbEx)
                    {
                        foreach (var validationError in dbEx.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors))
                        {
                            System.Diagnostics.Trace.WriteLine(validationError.PropertyName + " " + validationError.ErrorMessage);
                        }
                    }
                }
            }

        }

        protected void RedirectBack(object sender, EventArgs e)
        {
            Response.Redirect("Groups.aspx");
        }
    }
}